package com.education.teacher.exception;

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.InvalidSessionException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.education.exception.ServiceException;
import com.education.model.ErrorCode;
import com.education.model.ResultDo;

/**
 * @author Administrator
 */
@RestControllerAdvice
public class GlobExceptionHandle {
    /**
     *
     */
    private static Logger LOGGER = LogManager.getLogger(GlobExceptionHandle.class.getName());

    /**
     * 返回http 500 状态码
     * @param e 自定义异常
     * @return ResultDo<>
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(reason = "服务层异常",value =HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultDo<?> handleException(ServiceException e) {
        e.printStackTrace();
        LOGGER.error(e.getStackTrace());
        return new ResultDo<>(500,"服务层异常");
    }

    /**
     * 无权访问处理，返回401状态码
     * 2017/8/16 新增 by 雷紫辉
     * @param e
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(reason = "无权访问！",value =HttpStatus.UNAUTHORIZED)
    public ResultDo<?> handleException(UnauthorizedException e) {
        LOGGER.error(e.getStackTrace());
        e.printStackTrace();
        return new ResultDo<>(401,"无权访问!");
    }

    /**
     * 会话过期异常
     * 会返回一个http错误状态码 前台可用axios 拦截器进行拦截处理
     * 2017/8/16 增加 by 雷紫辉
     *
     * @param e
     */
    @ExceptionHandler(InvalidSessionException.class)
    @ResponseStatus(reason = "登陆状态已过期", value = HttpStatus.FORBIDDEN)//返回403状态码
    public ResultDo<?> handleException(InvalidSessionException e) {
        LOGGER.error(e.getStackTrace());
        e.printStackTrace();
        return new ResultDo<>(403,"登陆状态失效！");
    }

    /**
     * @param e 其他异常处理
     * @return ResultDo<Void>
     * 2017/8/7 修改 by 雷紫辉 修改返回值为标准的ResultDo
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(reason = "Exception",value =HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultDo<Void> handleException(Exception e) {
        LOGGER.error(e.getStackTrace());
        e.printStackTrace();
        return new ResultDo<>(500, "未知异常");
    }

}
